package google.usingblobstore;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A servlet that handles post uploads.
 * 
 * @author eschoeffler@google.com (Eric Schoeffler)
 */
@SuppressWarnings("serial")
public class PostUploadServlet extends HttpServlet {
  
  private BlobstoreService blobstoreService;
  private DatastoreService datastore;
  
  public PostUploadServlet() {
    blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    datastore = DatastoreServiceFactory.getDatastoreService();
  }
  
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);

    BlobKey blobKey = blobs.get("file");
    BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
    BlobInfo blobInfo = blobInfoFactory.loadBlobInfo(blobKey);
    saveBlobInfo(blobInfo.getFilename(), blobInfo);
    resp.sendRedirect("/");
  }
  
  public void saveBlobInfo(String filename, BlobInfo blobInfo) {
    Entity blobData = new Entity("Blob", filename);
    blobData.setProperty("blob_info", blobInfo.getBlobKey());
    datastore.put(blobData);
  }
}